import 'package:star_author/config/app.dart';
import 'package:star_author/utils/common_util/num_util.dart';
import 'package:star_author/utils/event.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/statistics/event/backflow_event.dart';
import 'package:star_author/utils/statistics/huiliu/event.dart';
import 'package:star_author/utils/statistics/huiliu/huiliu_statistics.dart';
import 'package:star_author/utils/statistics/statistics.dart';
import 'package:star_author/views/products/bidding_product_list_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_aliplayer/flutter_alilistplayer.dart';
import 'package:flutter_aliplayer/flutter_aliplayer.dart';
import 'package:flutter_aliplayer/flutter_aliplayer_factory.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_notification/pull_to_refresh_notification.dart';
import 'package:wakelock/wakelock.dart';

import '../../../config/base_configuration.dart';
import '../../../config/ui_constant.dart';
import '../../../generated/json/base/json_convert_content.dart';
import '../../../utils/http/http_util.dart';
import '../../../utils/string_util.dart';
import '../../../utils/utils.dart';
import '../../../widgets/button_widget.dart';
import '../../../widgets/cover_widget.dart';
import '../../products/bidder_goods_detail_page/bidder_goods_detaill_page.dart';
import '../model/live_good_list_entity.dart';

class LiveRecordingDialogUtil {
  static showDialog(
    recording_video,
    liveId,
    item, {
    LiveRecordForm liveRecordForm: LiveRecordForm.Living,
    bool isMall: false,
  }) async {
    if (liveRecordForm == LiveRecordForm.Living) {
      //关闭声音模块
      await StreamConf.engine.disableAudio();
    }
    Get.dialog(LiveRecordingDialog(
      recording_video: recording_video,
      liveRecordForm: liveRecordForm,
      liveId: liveId,
      item: item,
      isMall: isMall,
    )).then((value) async {
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarBrightness: Brightness.light,
      ));
      if (liveRecordForm == LiveRecordForm.Living ||
          (item['is_living'] ?? false)) {
        //退出录播观看页面 开启直播间声音模块
        await StreamConf.engine.enableAudio();
      }
    });
  }
}

enum LiveRecordForm {
  Living,
  DetailToLiving,
  DetailNoLiving,
}

//录制视频播放
class LiveRecordingDialog extends StatefulWidget {
  String recording_video;
  LiveRecordForm liveRecordForm;
  Map<String, dynamic> item; //当前点击的
  int liveId;
  bool isMall;

  LiveRecordingDialog({
    Key? key,
    this.recording_video: "",
    this.liveRecordForm: LiveRecordForm.Living,
    this.item: const {},
    this.liveId: -1,
    this.isMall: false,
  }) : super(key: key);

  @override
  State<LiveRecordingDialog> createState() => _LiveRecordingDialogState();
}

class _LiveRecordingDialogState extends State<LiveRecordingDialog>
    with WidgetsBindingObserver {
  //创建播放列表
  FlutterAliListPlayer fAliListPlayer =
      FlutterAliPlayerFactory.createAliListPlayer(playerId: 'aliListPlayer');

  Map map = {
    LiveRecordForm.Living: "直播间",
    LiveRecordForm.DetailNoLiving: "竞标详情",
    LiveRecordForm.DetailToLiving: "竞标详情",
  };

  //播放器配置
  var configMap = {
    'mStartBufferDuration': 30 * 1000, //起播缓冲区时长，单位：毫秒
    'mHighBufferDuration': 20 * 1000, //高缓冲时长，单位：毫秒
    'mMaxBufferDuration': 30 * 1000, //最大缓冲区时长，单位：毫秒
    'mNetworkTimeout': 30 * 1000, //网络超时时间，单位：毫秒
    'mNetworkRetryCount': 3, //网络超时重试次数，单位：毫秒
    'mMaxProbeSize': 30 * 1024 * 1024, //最大probe大小
    'mReferrer': 3, //设置referrer
    'mEnableSEI': false, //是否启用SEI
    'mClearFrameWhenStop': false, //停止后是否清空画面
    'mDisableVideo': false, //禁用Video
    'mDisableAudio': false, //禁用Audio
    'mUserAgent': "Exoplayer", //设置UserAgent
  };

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Wakelock.enable();
    FlutterAliplayer.enableConsoleLog(false);
    fAliListPlayer.setCacheConfig(App.ali_setting);
    HuiLiuStatistics().event(HuiLiuEvent.view_backflow_recording_video, {
      'id': widget.item['id'] ?? 0,
    });
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      Future.delayed(Duration(milliseconds: 500), () {
        addListener();
        listVideoUrl.add(widget.recording_video);
        //uid是视频的唯一标志。用于区分视频是否一样。如果uid一样，则认为是一样的
        fAliListPlayer.addUrlSource(
          uid: widget.recording_video,
          url: widget.recording_video,
        );
        data.add(LiveGoodListData.fromJson(widget.item));
        if ([LiveRecordForm.Living, LiveRecordForm.DetailToLiving]
            .contains(widget.liveRecordForm)) {
          WidgetsBinding.instance!.addPostFrameCallback((timeStamp) async {
            await getRecordingList();
          });
        } else {
          WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
            _updateVideoUrl(listVideoUrl[0]);
          });
        }
      });
    });
    StatisticsUtil.event(
      SystemEvent.guan_kan_lu_bo,
      {
        "watch_form": map[widget.liveRecordForm],
      },
    );
  }

  bool isLoading = true; //是否显示loading

  bool is_paused = false; //是否暂停

  update() {
    if (mounted) setState(() {});
  }

  addListener() async {
    fAliListPlayer.setAutoPlay(true);
    //设置预加载个数。总共加载的个数为： 1 + count*2。
    fAliListPlayer.setPreloadCount(2);
    fAliListPlayer.setOnPrepared((playerId) {
      //在prepare成功之后，通过getMediaInfo可以获取到各个码流的信息，
      fAliListPlayer.getMediaInfo().then((value) {
        _videoDuration =
            NumUtil.divide((value['duration'] ?? 1000), 1000).toInt();
        update();
      });
    });
    //设置宽高比适应（将按照视频宽高比等比缩小到view内部，不会有画面变形）
    fAliListPlayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFIT);
    //设置宽高比填充（将按照视频宽高比等比放大，充满view，不会有画面变形）
    //fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALEASPECTFILL);
    // //设置拉伸填充（如果视频宽高比例与view比例不一致，会导致画面变形）
    //fAliplayer.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALETOFILL);

    fAliListPlayer.setOnStateChanged((newState, playerId) {
      switch (newState) {
        //正在播放
        case FlutterAvpdef.AVPStatus_AVPStatusStarted:
          isLoading = false;
          is_paused = false;
          update();
          break;
        //播放暂停
        case FlutterAvpdef.AVPStatus_AVPStatusPaused:
          is_paused = true;
          isLoading = false;
          update();
          break;
        default:
      }
    });

    fAliListPlayer.setOnError((errorCode, errorExtra, errorMsg, playerId) {
      Fluttertoast.showToast(msg: errorMsg ?? "");
    });
    //播放器事件信息回调，包括buffer、当前播放进度等等信息，根据infoCode来判断，对应FlutterAvpdef.infoCode
    fAliListPlayer.setOnInfo((infoCode, extraValue, extraMsg, playerId) {
      if (infoCode == FlutterAvpdef.CURRENTPOSITION) {
        int current = NumUtil.divide(extraValue ?? 1000, 1000).toInt();
        _currentDuration = current;
        update();
        // LogUtil.v("当前播放:${current}");
      }
    });
    fAliListPlayer.setOnCompletion((playerId) {
      is_paused = true;
      isLoading = false;
      update();
    });
  }

  int seep = 10; //默认视频长度为10s

  late int _videoDuration = 10; // 当视频播放时  total = current + sep;

  late int _currentDuration = 0;

  var x = 0.0;
  var y = 0.0;

  List<String> listVideoUrl = [];

  List<LiveGoodListData> data = [];

  //获取录播集合
  getRecordingList() async {
    Map<String, dynamic>? map = {
      "with_recording_video": true,
      "per_page": 20,
    };
    await HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/studios/${widget.liveId}/backflows',
      isLoading: false,
      isErrorToast: false,
      queryParameters: map,
    ).then((value) async {
      LiveGoodListEntity? entity =
          JsonConvert.fromJsonAsT<LiveGoodListEntity>(value.data);
      List<LiveGoodListData> list = entity?.data ?? [];
      list.removeWhere(
          (element) => element.recordingVideo == widget.recording_video);
      data.addAll(list);
      for (int i = 0; i < list.length; i++) {
        listVideoUrl.add(list[i].recordingVideo ?? "");
        fAliListPlayer.addUrlSource(
          uid: list[i].recordingVideo ?? "",
          url: list[i].recordingVideo ?? "",
        );
      }
      _updateVideoUrl(listVideoUrl[0]);
    });
  }

  /// 更新播放器
  _updateVideoUrl(String url) async {
    fAliListPlayer.stop();
    //uid为必填项，如果是URL播放方式，只需要uid即可，如果是STS方式，则需要填写STS信息
    fAliListPlayer.moveTo(uid: url);
  }

  //是否自动播放
  bool loop = true;

  /// true ？ 加载成功 ： 加载中
  bool _loadVideoOK = false;

  Widget loadingWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          alignment: Alignment.center,
          child: Text(
            '加载中',
            style: TextStyle(fontSize: 18.sp, color: Colors.white),
          ),
        ),
        SizedBox(
          height: 5,
        ),
        Container(
          child: Center(
            child: CupertinoActivityIndicator(
              activeColor: Colors.white,
              radius: 10.w,
            ),
          ),
        )
      ],
    );
  }

  bool is_show_speed = false;

  int current_speed = 2;

  List speedList = [
    {
      "title": "0.5X",
      "value": 0.5,
    },
    {
      "title": "0.75X",
      "value": 0.75,
    },
    {
      "title": "1X",
      "value": 1.0,
    },
    {
      "title": "1.25X",
      "value": 1.25,
    },
    {
      "title": "1.5X",
      "value": 1.5,
    },
    {
      "title": "2X",
      "value": 2.0,
    },
  ];

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.resumed:
        is_paused = false;
        fAliListPlayer.play();
        break;
      case AppLifecycleState.paused:
        is_paused = true;
        fAliListPlayer.pause();
        break;
      case AppLifecycleState.detached:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black.withOpacity(0.15),
      child: Container(
        width: Get.width,
        height: Get.height,
        alignment: Alignment.center,
        child: Stack(
          children: [
            //添加播放器为透明 加载成功后显示
            Opacity(
              opacity: isLoading ? 0.15 : 1,
              child: AliPlayerView(
                onCreated: onViewPlayerCreated,
                x: x,
                y: y,
                width: Get.width,
                height: Get.height,
              ),
            ),
            if (isLoading)
              Container(
                color: Colors.black.withOpacity(0.15),
                width: Get.width,
                height: Get.height - Get.statusBarHeight,
                child: loadingWidget(),
              ),
            Container(
              child: Center(
                child: !is_paused
                    ? Container()
                    : RoucesUtil.getAssetsIcon('ic_live_player_start_lt', 32.w),
              ),
            ),
            if (data.length > 0 &&
                (data[currentIndex].anchor_nickname ?? "").isNotEmpty)
              Container(
                padding: EdgeInsets.symmetric(
                  horizontal: 14.w,
                  vertical: 7.w,
                ),
                margin: EdgeInsets.only(
                  left: 12.w,
                  top: 20.w,
                ),
                decoration: BoxDecoration(
                  color: rgba(0, 0, 0, 0.30),
                  borderRadius: BorderRadius.circular(19),
                ),
                child: Text(
                  "讲解主播: ${data[currentIndex].anchor_nickname ?? ""}",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                    fontSize: 12.sp,
                  ),
                ),
              ),
            if (data.length > 0 &&
                ((data[currentIndex].priceRange?.length) != 0 ||
                    (data[currentIndex].priceRange?.length) != 0))
              Container(
                padding: EdgeInsets.symmetric(
                  horizontal: 14.w,
                  vertical: 7.w,
                ),
                margin: EdgeInsets.only(
                  left: 12.w,
                  top: 65.w,
                ),
                decoration: BoxDecoration(
                  color: rgba(0, 0, 0, 0.30),
                  borderRadius: BorderRadius.circular(19),
                ),
                child: Text(
                  "源头市场价: ${getPriceWithList(
                    (data[currentIndex].priceRange?.length) != 0
                        ? data[currentIndex].priceRange ?? []
                        : data[currentIndex].appraisalPrice ?? [],
                    intl: true,
                    show_name: data[currentIndex].price_range_show_name ?? "",
                  )}",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                    fontSize: 12.sp,
                  ),
                ),
              ),
            //全屏点击
            GestureDetector(
              child: Container(
                color: Colors.black.withOpacity(0.15),
                width: Get.width,
                height: Get.height,
              ),
              behavior: HitTestBehavior.opaque,
              onTap: () {
                if (is_paused) {
                  if (_currentDuration == _videoDuration) {
                    //播放完成 跳转到第一个位置 = 重新播放
                    fAliListPlayer.seekTo(1000, FlutterAvpdef.INACCURATE);
                    fAliListPlayer.play();
                  } else {
                    fAliListPlayer.play();
                  }
                } else {
                  double offset = (height + 12.w) * (currentIndex);
                  if (data.length > 1) {
                    //需要加延迟 不然跳转不了
                    Future.delayed(Duration(milliseconds: 400), () {
                      scrollController.animateTo(offset,
                          duration: Duration(milliseconds: 600),
                          curve: Curves.easeInOut);
                    });
                  }
                  fAliListPlayer.pause();
                }
                is_paused = !is_paused;
                update();
              },
              onLongPressStart: (LongPressStartDetails details) {
                fAliListPlayer.setRate(2.0);
              },
              onLongPressEnd: (LongPressEndDetails details) {
                fAliListPlayer.setRate(1.0);
              },
            ),
            Container(
              margin: EdgeInsets.only(
                  left: 12.w,
                  top: 12.w,
                  right: 12.w,
                  bottom: MediaQuery.of(context).padding.bottom + 12.w),
              child: buildBottomWidget(),
              alignment: Alignment.bottomCenter,
            ),
            if ([LiveRecordForm.Living, LiveRecordForm.DetailToLiving]
                .contains(widget.liveRecordForm))
              Container(
                alignment: Alignment.bottomCenter,
                margin: EdgeInsets.only(
                    top: 12.w,
                    bottom: MediaQuery.of(context).padding.bottom + 120.w),
                child: buildRecordingGood(),
              ),
            if ([LiveRecordForm.DetailToLiving].contains(widget.liveRecordForm))
              Positioned(
                child: Container(
                  child: GestureDetector(
                    child: Container(
                      alignment: Alignment.centerRight,
                      child: Image.asset(
                        "images/live_close.png",
                        width: 30.0.w,
                        height: 30.0.w,
                        fit: BoxFit.cover,
                      ),
                    ),
                    behavior: HitTestBehavior.opaque,
                    onTap: () async {
                      Get.back();
                    },
                  ),
                ),
                left: 12.w,
                right: 20.w,
                top: MediaQuery.of(context).padding.top + 20.w,
              ),
            if (!isLoading)
              Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    if (is_show_speed)
                      Container(
                        alignment: Alignment.bottomCenter,
                        width: Get.width - 24.w,
                        height: 36.w,
                        decoration: BoxDecoration(
                            color: rgba(0, 0, 0, 0.30),
                            borderRadius: BorderRadius.circular(25)),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: List.generate(
                            speedList.length,
                            (index) => GestureDetector(
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  if (current_speed == index)
                                    AnimatedContainer(
                                      duration: Duration(milliseconds: 300),
                                      child: Container(
                                        width: 36.w,
                                        height: 36.w,
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius:
                                              BorderRadius.circular(50.w),
                                        ),
                                      ),
                                    ),
                                  Container(
                                    alignment: Alignment.center,
                                    width:
                                        (Get.width - 24.w) / speedList.length,
                                    child: Text(
                                      speedList[index]['title'],
                                      style: TextStyle(
                                        fontSize: 12.sp,
                                        color: current_speed == index
                                            ? UIConstant.colorE02020
                                            : rgba(255, 255, 255, 1),
                                        fontWeight: current_speed == index
                                            ? FontWeight.w500
                                            : FontWeight.w400,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              behavior: HitTestBehavior.opaque,
                              onTap: () async {
                                setState(() {
                                  current_speed = index;
                                  is_show_speed = !is_show_speed;
                                });
                                //设置倍速播放：支持0.5～5倍速的播放，通常按0.5的倍数来设置，例如0.5倍、1倍、1.5倍等
                                await fAliListPlayer
                                    .setRate(speedList[index]['value']);

                                if (is_paused) {
                                  fAliListPlayer.play();
                                }
                              },
                            ),
                          ),
                        ),
                        margin: EdgeInsets.only(
                          bottom: 10.w,
                          left: 12.w,
                          right: 12.w,
                        ),
                      ),
                    Container(
                      width: double.infinity,
                      child: Row(
                        children: [
                          Expanded(
                              child: Container(
                            height: 36.w,
                            margin: EdgeInsets.symmetric(horizontal: 12.w),
                            padding: EdgeInsets.symmetric(horizontal: 15.w),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: Color(0x4D000000),
                                borderRadius: BorderRadius.circular(25)),
                            child: Container(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.zero,
                                    child: SliderTheme(
                                      data: SliderTheme.of(context).copyWith(
                                        //已拖动的颜色
                                        activeTrackColor: Color(0xCCD8D8D8),
                                        //未拖动的颜色
                                        inactiveTrackColor: Color(0x36D8D8D8),
                                        //提示进度的气泡的背景色
                                        valueIndicatorColor: Color(0xCCD8D8D8),
                                        //提示进度的气泡文本的颜色
                                        valueIndicatorTextStyle: TextStyle(
                                          color: Colors.white,
                                        ),
                                        trackHeight: 4.w,
                                        tickMarkShape: RoundSliderTickMarkShape(
                                          //继承SliderTickMarkShape可自定义刻度形状
                                          tickMarkRadius: 0, //刻度大小
                                        ),
                                        thumbShape: RoundSliderThumbShape(
                                          //可继承SliderComponentShape自定义形状
                                          disabledThumbRadius: 0, //禁用时滑块大小
                                          enabledThumbRadius: 3.w, //滑块大小
                                        ),
                                        overlayShape: RoundSliderOverlayShape(
                                          //可继承SliderComponentShape自定义形状
                                          overlayRadius: 0, //滑块外圈大小
                                        ),

                                        //滑块中心的颜色
                                        thumbColor: Colors.white,
                                      ),
                                      child: Slider(
                                        value: _currentDuration.toDouble(),
                                        max: _videoDuration.toDouble(),
                                        divisions: _videoDuration.toInt(),
                                        label:
                                            "${StringUtil.toTwoDigits(Duration(seconds: _currentDuration.toInt()).inHours.remainder(24))}:${StringUtil.toTwoDigits(Duration(seconds: _currentDuration.toInt()).inMinutes.remainder(60))}:${StringUtil.toTwoDigits(Duration(seconds: _currentDuration.toInt()).inSeconds.remainder(60))}",
                                        onChanged: (double value) {
                                          _currentDuration = value.toInt();
                                          //接口为毫秒 需要*1000
                                          fAliListPlayer.seekTo(
                                            _currentDuration * 1000,
                                            FlutterAvpdef.INACCURATE,
                                          );
                                          fAliListPlayer.play();
                                          update();
                                        },
                                      ),
                                    ),
                                    height: 10.w,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        "${StringUtil.toTwoDigits(Duration(seconds: _currentDuration.toInt()).inHours.remainder(24))}:${StringUtil.toTwoDigits(Duration(seconds: _currentDuration.toInt()).inMinutes.remainder(60))}:${StringUtil.toTwoDigits(Duration(seconds: _currentDuration.toInt()).inSeconds.remainder(60))}",
                                        style: TextStyle(
                                          color: Color(0xFFEEEEEE),
                                          fontSize: 10.sp,
                                        ),
                                      ),
                                      Text(
                                        "${StringUtil.toTwoDigits(Duration(seconds: _videoDuration.toInt()).inHours.remainder(24))}:${StringUtil.toTwoDigits(Duration(seconds: _videoDuration.toInt()).inMinutes.remainder(60))}:${StringUtil.toTwoDigits(Duration(seconds: _videoDuration.toInt()).inSeconds.remainder(60))}",
                                        style: TextStyle(
                                          color: Color(0xFFEEEEEE),
                                          fontSize: 10.sp,
                                        ),
                                      ),
                                    ],
                                  )
                                ],
                              ),
                            ),
                          )),
                          GestureDetector(
                            child: Container(
                              margin: EdgeInsets.only(
                                right: 10.w,
                              ),
                              width: 36.w,
                              height: 36.w,
                              child: Center(
                                child: Text(
                                  "${speedList[current_speed]['title']}",
                                  style: TextStyle(
                                    fontSize: 12.sp,
                                    color: rgba(255, 255, 255, 1),
                                  ),
                                ),
                              ),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(50.w),
                                color: rgba(0, 0, 0, 0.30),
                              ),
                            ),
                            onTap: () {
                              setState(() {
                                is_show_speed = !is_show_speed;
                              });
                            },
                          )
                        ],
                      ),
                    ),
                  ],
                ), //是否可以跳转
                alignment: Alignment.bottomCenter,
                margin: EdgeInsets.only(
                    bottom: MediaQuery.of(context).padding.bottom + 62.w),
              ),
          ],
        ),
      ),
    );
  }

  ///4、设置播放源
  ///说明：STS 播放方式，vid、region、accessKeyId、accessKeySecret、securityToken 为必填，其他参数可选
  ///     AUTH 播放方式，vid、region、playAuth 为必填，其他参数可选
  /// 每个 Map 对应的key 在 flutter 的 Demo 的 config.dart 中查看，fAliplayer 为播放器对象，如果还未创建，参考后续文档创建播放器
  void onViewPlayerCreated(viewId) async {
    fAliListPlayer.setPlayerView(viewId);
  }

  int currentIndex = 0;

  ScrollController scrollController = ScrollController();

  buildCard(index) {
    List<Widget> buildColumns() {
      List<Widget> list = [];
      list.add(Expanded(
        child: Container(
          alignment: Alignment.centerLeft,
          child: Text(
            '${data[index].goods?.title ?? ""}',
            style: TextStyle(
              fontSize: 14.sp,
              color: UIConstant.color33,
            ),
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ));
      if (["waitconfirm", "onsale"].contains(data[index].status)) {
        list.add(Expanded(
            child: Container(
          width: width,
          height: height,
          alignment: Alignment.centerLeft,
          child: Text(
            "已结拍",
            style: TextStyle(fontSize: 14.sp, color: UIConstant.color99),
          ),
        )));
      } else {
        list.add(Expanded(
            child: Container(
          alignment: Alignment.centerLeft,
          child: Text.rich(
            TextSpan(
                text: '已有',
                style: TextStyle(fontSize: 12.sp, color: UIConstant.color99),
                children: [
                  TextSpan(
                    text: '${data[index].tendersCount}',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: UIConstant.colorFF8F00,
                    ),
                  ),
                  TextSpan(
                    text: '人出价',
                  ),
                ]),
          ),
        )));
        list.add(
          Expanded(
            child: Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ButtonWidget(
                    child: Text(
                      "去出价",
                      style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w500,
                          color: Colors.white),
                    ),
                    type: ButtonType.bgOrange,
                    width: 68,
                    height: 28,
                    onPressed: () {
                      Get.back();
                      Get.to(
                        BidderGoodsDetailPage(
                          id: data[index].id ?? 0,
                          formDetail: BiddingProductListItemFormType.Live,
                          isNeedShowPriceDialog: true,
                        ),
                        preventDuplicates: false,
                      );
                    },
                  )
                ],
              ),
              alignment: Alignment.centerRight,
            ),
          ),
        );
      }
      return list;
    }

    return GestureDetector(
      child: Container(
        height: height,
        width: width,
        alignment: Alignment.centerLeft,
        margin: EdgeInsets.only(left: 12.w),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.only(left: 6.w),
              child: PeopleCoverWidget(
                size: 88.w,
                cover: data[index].goods?.cover?.url ?? "",
              ),
            ),
            Expanded(
              child: Container(
                alignment: Alignment.centerLeft,
                height: height,
                margin: EdgeInsets.only(
                  left: 10.w,
                  right: 10.w,
                ),
                child: Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: buildColumns(),
                  ),
                  height: 88.w,
                ),
              ),
            )
          ],
        ),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.w),
        ),
      ),
      onTap: () {
        changedIndex(index);
      },
    );
  }

  changedIndex(int index) {
    if (currentIndex != index) {
      if (index > 0) {
        double offset = (height + 12.w) * (index);
        scrollController.animateTo(offset,
            duration: Duration(milliseconds: 600), curve: Curves.easeInOut);
      }
      isLoading = true;
      is_paused = false;
      update();
      StatisticsUtil.event(
          SystemEvent.guan_kan_lu_bo_qi_ta_huo_pin_dian_ji, {});
      _updateVideoUrl(listVideoUrl[index]);
    }
    currentIndex = index;
    update();
  }

  double height = 100.w;
  double width = Get.width * 0.74;

  //显示已经录播的商品
  buildRecordingGood() {
    if (widget.item['goods']['category_prefix'] == "G") {
      return Container();
    }
    if (isLoading) {
      return Container();
    }
    if (!is_paused) {
      return Container();
    }
    if (listVideoUrl.length == 0) {
      return Container();
    } else if (listVideoUrl.length == 1) {
      return Container(
        child: buildCard(0),
        alignment: Alignment.bottomCenter,
      );
    }

    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(left: 12.w),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        controller: scrollController,
        padding: EdgeInsets.zero,
        child: Row(
          // controller: scrollController,
          // addAutomaticKeepAlives: false,
          // addRepaintBoundaries: false,
          children: List.generate(listVideoUrl.length, (index) {
            if (currentIndex == index) {
              return buildCard(index);
            }
            return GestureDetector(
              child: Container(
                  height: height,
                  width: height,
                  margin: EdgeInsets.only(left: 12.w),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8.w),
                      color: Colors.white),
                  alignment: Alignment.center,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      PeopleCoverWidget(
                        size: 85.w,
                        cover: data[index].goods?.cover?.url ?? "",
                      ),
                      Center(
                        child: RoucesUtil.getAssetsIcon('ic_live_play_lt', 25.w),
                      )
                    ],
                  )),
              onTap: () {
                changedIndex(index);
              },
            );
          }),
          // padding: EdgeInsets.zero,
          // scrollDirection: Axis.horizontal,
        ),
      ),
      height: 100.w,
      width: double.infinity,
    );
  }

  buildBottomWidget() {
    String text = "回到直播中";
    if (widget.liveRecordForm == LiveRecordForm.DetailNoLiving) {
      text = "退出观看";
    }
    return Container(
      height: 40.w,
      alignment: Alignment.bottomCenter,
      child: ButtonWidget(
        child: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Icon(
                Icons.arrow_back_ios,
                size: 12.w,
                color: Colors.white,
              ),
              SizedBox(
                width: 10.w,
              ),
              Text(
                text,
                style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                    color: Colors.white),
                textAlign: TextAlign.center,
                textDirection: TextDirection.ltr,
              )
            ],
          ),
        ),
        type: ButtonType.bgGradientRed,
        width: Get.width * 0.7,
        height: 40,
        onPressed: () {
          Get.back();
          //直播间进入
          if ((widget.item['is_living'] ?? false)) {
            Get.back();
          } else if (widget.liveRecordForm == LiveRecordForm.DetailToLiving) {
            if (widget.item['goods']['category_prefix'] == "G") {
            } else {}
          }
        },
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    this.fAliListPlayer.clear();
    this.fAliListPlayer.stop();
    this.fAliListPlayer.destroy();
    WidgetsBinding.instance?.removeObserver(this);
    Event.emit("wake_lock");
    Wakelock.disable();
  }
}
